package com.motu.monstercity.server.game.logic;

import com.motu.monstercity.module.common.servermanager.ServerInfo;
import com.motu.monstercity.module.common.servermanager.ServerManager;
import com.motu.monstercity.protocol.Common;
import com.motu.monstercity.protocol.CsGameSystem;
import com.motu.monstercity.server.game.base.AllParam;
import com.motu.monstercity.server.game.base.CommonUtils;
import com.motu.monstercity.server.game.base.LockKey;
import com.motu.monstercity.server.game.base.ProtoDataUtils;
import com.motu.monstercity.server.game.commondata.act.Act;
import com.motu.monstercity.server.game.commondata.act.ActConstant;
import com.motu.monstercity.server.game.commondata.act.ActConventionTask;
import com.motu.monstercity.server.game.commondata.mail.MailConstant;
import com.motu.monstercity.server.game.commondata.maintask.MainTaskConstant;
import com.motu.monstercity.server.game.commondata.rank.RankConstant;
import com.motu.monstercity.server.game.commondata.rank.RankReward;
import com.motu.monstercity.server.game.commondata.system.SystemConstant;
import com.motu.monstercity.server.game.commondata.union.UnionActionTaskConstant;
import com.motu.monstercity.server.game.commondata.union.UnionactionMain;
import com.motu.monstercity.server.game.commondata.union.UnionactionTaskType;
import com.motu.monstercity.server.game.commondata.world.WorldConstant;
import com.motu.monstercity.server.game.log.LogType;
import com.motu.monstercity.server.game.log.MotuLogManager;
import com.motu.monstercity.server.game.userdata.*;
import com.motu.monstercity.server.game.verticle.MainVerticle;
import com.motu.vertx.module.utility.main.MainService;
import com.motu.vertx.module.utility.model.EntityManager;
import com.motu.vertx.module.utility.redis.RedisTools;
import com.motu.vertx.module.utility.toolset.ErrorWord;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.json.JsonArray;
import io.vertx.core.shareddata.Lock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;

public class UnionMobileManager extends UnionMobileUserData {
    private static Logger logger = LoggerFactory.getLogger(UnionMobileManager.class);


    // 更新联盟总动员的个人排行榜
    public static void updateUnionMobileUserRank(Act act, UserInfo userInfo, long unionId, long score) {
        long userId = userInfo.getId();
        int serverId = userInfo.getServerId();
        if (!isDuringTime(act)) { // 如果不是进行期返回
            return;
        }
        String dateKey = String.valueOf(act.getId());
        RankManager.updateRank(RankConstant.SERVER_RANK_MOBILE, serverId, userId, score, dateKey);//  时间key
        updateUnionMobileUnionRank(act, userInfo, unionId, score); // 更新联盟的总积分排行
    }

    // 更新联盟总动员的联盟排行榜
    public static void updateUnionMobileUnionRank(Act act, UserInfo userInfo, long unionId, long score) {
        long userId = userInfo.getId();
        int serverId = userInfo.getServerId();
        if (!isDuringTime(act)) { // 如果不是进行期返回
            return;
        }
        //更新跨服排行榜
        String dateKey = String.valueOf(act.getId());
        int serverGroup = ServerManager.getWarZoneId(serverId);
        RankManager.updateRank(RankConstant.SERVER_UNION_RANK_MOBILE, serverGroup, unionId, score, dateKey);//  时间key
    }


    /**
     * 尝试刷新任务
     */
    public static void tryRefreshTask(long userId, long unionId, Common.PBUserData.Builder pbUserData) {
        refreshUserTask(userId, unionId); // 刷新专属任务
        refreshUnionTask(userId, unionId, pbUserData); // 自动刷公共任务
    }


    /**
     * 刷新个人任务
     *
     * @param userId
     * @return
     */
    public static void refreshUserTask(long userId, long unionId) {
        long nowTime = TimeUtils.getCurTime();
        List<UserMobileTaskInfo> taskInfos = getUserMobileTaskList(userId);
        Set<Integer> alreadyTaskIds = getAlreadyTaskIds(unionId, userId, null, taskInfos);
        if (taskInfos.isEmpty()) {    // 这里应该是要刷新出来所有任务
            int taskType1Init = AllParam.UNIONMOBILE_TASK_TYPE1_INIT;
            int taskType2Init = AllParam.UNIONMOBILE_TASK_TYPE2_INIT;
            List<Integer> task1List = randomTask(taskType1Init, alreadyTaskIds);
            List<Integer> task2List = randomTask(taskType2Init, alreadyTaskIds);
            createUserTasks(userId, 0, task1List, UnionActionTaskConstant.TASK_TYPE_1);
            createUserTasks(userId, 0, task2List, UnionActionTaskConstant.TASK_TYPE_2);
        } else {
            UserMobileInfo userMobileInfo = getUserMobileInfo(userId);
            for (UserMobileTaskInfo taskInfo : taskInfos) {
                if (taskInfo.isComplete()) continue; // 是完成状态冻结
                if (taskInfo.getRefreshTime() == 0 || nowTime < taskInfo.getRefreshTime()) continue;
                // 刷新一个任务出来代替
                List<Integer> taskList = randomTask(1, alreadyTaskIds);
                createUserTasks(userId, 0, taskList, taskInfo.getTaskType());
                if (taskInfo.getTaskId() == userMobileInfo.getTaskId()) {
                    userMobileInfo.resetCurTask();
                }
                taskInfo.delete();  // 删除原来旧的
            }
        }
    }

    /**
     * 刷新个人任务具体任务
     *
     * @param userId
     * @return
     */
    public static ErrorWord refreshUserTask(long userId, int taskId, Common.PBUserData.Builder pbUserData) {
        long nowTime = TimeUtils.getCurTime();
        UserMobileInfo userMobileInfo = getUserMobileInfo(userId);
        if (userMobileInfo.getTaskId() == taskId) {
            return ErrorWord.NOT_DATA_1;
        }
        UserMobileTaskInfo taskInfo = getUserMobileTaskInfo(userId, taskId);
        if (taskInfo == null) {
            return ErrorWord.NOT_DATA_2;
        }
        if (taskInfo.getRefreshTime() != 0) return ErrorWord.NOT_DATA_3;
        if (taskInfo.getIsComplete() != 0) {  // 如果已经被接取了不能刷新
            return ErrorWord.NOT_DATA_4;
        }
        taskInfo.putRefreshTime(nowTime + (long) TimeUtils.MINUTE * AllParam.UNIONMOBILE_NO_ACCEPT_TIME);  // 下次刷新时间
        taskInfo.update();
        ProtoDataUtils.updatePBUserData(pbUserData, taskInfo);
        return null;
    }

    /**
     * 通用方法：批量创建用户任务
     */
    private static void createUserTasks(long userId, long refreshTime,
                                        List<Integer> taskIds, int taskType) {
        for (int taskId : taskIds) {
            UserMobileTaskInfo task = new UserMobileTaskInfo(userId, taskId, taskType, refreshTime);
            task.doCreate();
        }
    }


    // 手动刷新公共任务
    public static ErrorWord refreshUnionTask(long userId, int taskId, UserUnion userUnion, Common.PBUserData.Builder pbUserData) {
        if (!userUnion.IsPostElite()) {
            return ErrorWord.NOT_DATA_1;
        }
        long nowTime = TimeUtils.getCurTime();
        UserMobileInfo userMobileInfo = getUserMobileInfo(userId);
        if (userMobileInfo.getTaskId() == taskId) {
            return ErrorWord.NOT_DATA_2;
        }
        UnionMobileTaskInfo unionMobileTaskInfo = getUnionMobileTaskInfo(userUnion.getUnionId(), taskId);
        if (unionMobileTaskInfo == null) {
            return ErrorWord.NOT_DATA_3;
        }
        if (unionMobileTaskInfo.getIsComplete() != 0) {
            return ErrorWord.NOT_DATA_4;
        }
        if (nowTime < unionMobileTaskInfo.getRefreshTime()) {
            return ErrorWord.NOT_DATA_5;
        }
        UnionactionTaskType unionactionTaskType = getUnionactionTaskType(UnionActionTaskConstant.TASK_TYPE_3);
        if (unionactionTaskType == null) {
            return ErrorWord.NOT_DATA_6;
        }
        Lock lock = null;
        try {
            lock = MainService.getVertLock(LockKey.getUnionMobileLock(userId));
            if (nowTime < unionMobileTaskInfo.getRefreshTime()) {
                return ErrorWord.NOT_DATA_6;
            }
            unionMobileTaskInfo.putRefreshTime(nowTime + unionactionTaskType.getCd());
            unionMobileTaskInfo.update();
            ProtoDataUtils.updatePBUserData(pbUserData, unionMobileTaskInfo);
        } catch (Exception e) {
            logger.info("联盟总动员手动刷新公共任务,userId:{},error:{}", userId, e.getMessage());
        } finally {// 释放锁
            MainService.releaseVertLock(lock);
        }
        // 推送联盟公共任务信息给联盟其他成员
        BoardcastManager.publicUnionMobileTask(GameUser.getUserInfo(userId), userUnion.getUnionId(), unionMobileTaskInfo);
        return null;
    }

    /**
     * 刷新联盟任务
     *
     * @param userId
     * @return
     */
    public static void refreshUnionTask(long userId, long unionId, Common.PBUserData.Builder pbUserData) {
        // 是否有精英以权限
        long nowTime = TimeUtils.getCurTime();
        UnionMobileInfo unionMobileInfo = getUnionMobileInfo(unionId);
        if (nowTime < unionMobileInfo.getNextRefreshTime()) { // 没有到自动刷新时间
            return;
        }
        // 刷新公共任务加锁
        List<UnionMobileTaskInfo> unionMobileTaskInfos = new ArrayList<>();
        Set<Integer> alreadyTaskIds = getAlreadyTaskIds(unionId, userId, unionMobileTaskInfos, null);
        Lock lock = null;
        try {
            lock = MainService.getVertLock(LockKey.getUnionMobileLock(userId));
            if (nowTime < unionMobileInfo.getNextRefreshTime()) { // 没有到自动刷新时间  直接退出
                return;
            }
            unionMobileTaskInfos = getUnionMobileTaskList(unionId);
            if (unionMobileTaskInfos.isEmpty()) {  //  这里应该是要刷新出来所有任务 走新建
                List<Integer> taskList = randomTask(AllParam.UNIONMOBILE_TASK_TYPE3_INIT, alreadyTaskIds);
                for (int taskId : taskList) {
                    UnionMobileTaskInfo unionMobileTaskInfo = new UnionMobileTaskInfo(unionId, taskId);
                    unionMobileTaskInfo.doCreate();
                }
            } else {
                for (UnionMobileTaskInfo taskInfo : unionMobileTaskInfos) {
                    if (taskInfo.getUserId() != 0 && nowTime < taskInfo.getRefreshTime()) continue;  // 已接取的任务还未到过期时间 跳过
                    if (taskInfo.isComplete()) continue; // 已完成的需要跳过
                    if (taskInfo.getUserId() != 0) {
                        UserMobileInfo userMobileInfo = getUserMobileInfo(taskInfo.getUserId());
                        userMobileInfo.resetCurTask();
                        if (taskInfo.getUserId() == userId) {
                            ProtoDataUtils.updatePBUserData(pbUserData, userMobileInfo);
                        }
                    }
                    List<Integer> taskList = randomTask(1, alreadyTaskIds);
                    if (!taskList.isEmpty()) {
                        taskInfo.putTaskId(taskList.getFirst());
                        taskInfo.putIsComplete(0);
                        taskInfo.putUserId(0);
                        taskInfo.putProgress(0);
                        taskInfo.putRefreshTime(0);//
                        taskInfo.update();
                    }
                }
            }
            UnionactionTaskType unionactionTaskType = getUnionactionTaskType(UnionActionTaskConstant.TASK_TYPE_3);
            // 算出半小时的周期，已经过了多少次半小时了，下次的半小时节点为新的刷新时间
            int intervalTime = unionactionTaskType.getCd();
            long nextRefreshTime = nowTime + ((long) unionactionTaskType.getCd());
            if (unionMobileInfo.getNextRefreshTime() != 0) {
                long interval = (nowTime - unionMobileInfo.getNextRefreshTime()) / intervalTime;  // 间隔了多少个半小时
                nextRefreshTime = unionMobileInfo.getNextRefreshTime() + (interval + 1) * intervalTime; // +1 为下一个周期
            }
            unionMobileInfo.putNextRefreshTime(nextRefreshTime);
            unionMobileInfo.update();
            ProtoDataUtils.updatePBUserData(pbUserData, unionMobileInfo);
        } catch (Exception e) {
            logger.info("联盟总动员刷新公共任务,userId:{},error:{}", userId, e.getMessage());
        } finally {// 释放锁
            MainService.releaseVertLock(lock);
        }


        for (UnionMobileTaskInfo unionMobileTaskInfo : unionMobileTaskInfos) {
            ProtoDataUtils.updatePBUserData(pbUserData, unionMobileTaskInfo);
        }
        // 推送联盟公共任务信息给联盟其他成员
        BoardcastManager.publicUnionMobileTask(GameUser.getUserInfo(userId), unionId, unionMobileTaskInfos);
    }

    /**
     * 处理任务进度
     */
    public static ErrorWord handleTaskProgress(Act act,
                                               UserInfo userInfo,
                                               UnionactionMain unionactionMain,
                                               UserMobileInfo userMobileInfo,
                                               int taskId, boolean isAdd, long num, Common.PBUserData.Builder pbUserData) {
        long userId = userInfo.getId();
        long progress = unionactionMain.getNum(); //  配置的进度
        UserUnion userUnion = UnionManager.getUserUnion(userId);
        if (!userMobileInfo.isUnionTask()) {
            UserMobileTaskInfo mobileTaskInfo = getUserMobileTaskInfo(userId, taskId);
            if (mobileTaskInfo == null) {
                return ErrorWord.NOT_DATA_1;
            }
            if (!mobileTaskInfo.canDo()) {
                return null;
            }

            if (isAdd) {
                mobileTaskInfo.addProgress(num);   // 增加进度
            } else {
                mobileTaskInfo.putProgress(num);   // 覆盖进度
            }
            if (mobileTaskInfo.getProgress() >= progress) {  // 完成了的话
                mobileTaskInfo.putIsComplete(UnionActionTaskConstant.TASK_COMPLETE);
            }
            mobileTaskInfo.update();
            ProtoDataUtils.updatePBUserData(pbUserData, mobileTaskInfo, true);
        } else {
            // 如果完成的是联盟任务,等待自动刷新
            UnionMobileTaskInfo unionMobileTaskInfo = getUnionMobileTaskInfo(userUnion.getUnionId(), taskId);
            if (unionMobileTaskInfo == null) {
                return ErrorWord.NOT_DATA_3;
            }
            if (!unionMobileTaskInfo.canDo()) {  // 已经完成了 不变化
                return null;
            }
            if (isAdd) {
                unionMobileTaskInfo.addProgress(num);   // 增加进度
            } else {
                unionMobileTaskInfo.putProgress(num);   // 覆盖进度
            }
            if (unionMobileTaskInfo.getProgress() >= progress) {  // 完成了的话
                unionMobileTaskInfo.putIsComplete(UnionActionTaskConstant.TASK_COMPLETE);
            }
            unionMobileTaskInfo.update();
            BoardcastManager.publicUnionMobileTask(userInfo, userUnion.getUnionId(), unionMobileTaskInfo);  // 同步其他盟友公共任务变化
            ProtoDataUtils.updatePBUserData(pbUserData, unionMobileTaskInfo, true);
        }
        return null;
    }


    /**
     * 判断是否满足解锁参与条件
     *
     * @param userInfo
     * @return
     */
    public static ErrorWord isUnlock(UserUnion userUnion, UserInfo userInfo) {
        long userId = userInfo.getId();
        if (userUnion.getUnionId() == 0) {
            return ErrorWord.MODULE_LOCKED; // 暂未开放
        }
        long memberCount = UnionManager.getUnionMemberNum(userUnion.getUnionId());
        if (memberCount < AllParam.UNIONMOBILE_JOIN_NUM) {
            return ErrorWord.MODULE_LOCKED; // 人员数量不满足
        }
        // 玩家都市等级\
        if (userInfo.getLevel() < AllParam.UNIONMOBILE_JOIN_LV) {
            return ErrorWord.LEVEL_LACK; // 都市等级不足
        }
        return null;
    }

    // 是否在进行中
    public static boolean isDuringTime(Act act) {
        if (act == null) {
            return false;
        }
        long nowTime = TimeUtils.getCurTime();
        //  获取
        long rewardTime = act.getEndTime() - TimeUtils.MINUTE * 30; // 公示期时间为结束前半小时
        return nowTime >= act.getStartTime() && nowTime <= rewardTime;
    }

    // 是否在领奖中
    public static boolean isRewardTime(Act act) {
        if (act == null) {
            return false;
        }
        long nowTime = TimeUtils.getCurTime();
        //  获取
        long rewardTime = act.getEndTime() - (long) TimeUtils.MINUTE * AllParam.UNIONMOBILE_PUBLIC_TIME; // 公示期时间为结束前半小时
        return nowTime >= rewardTime && nowTime <= act.getCloseTime();
    }

    /**
     * 獲取目前的任務Id
     *
     * @return
     */
    public static Set<Integer> getAlreadyTaskIds(long unionId, long userId, List<UnionMobileTaskInfo> unionMobileTaskList, List<UserMobileTaskInfo> unionMobileTaskInfos) {
        Set<Integer> taskIds = new HashSet<>();
        if (unionMobileTaskList == null) {
            unionMobileTaskList = getUnionMobileTaskList(unionId);
        }
        if (unionMobileTaskInfos == null) {
            unionMobileTaskInfos = getUserMobileTaskList(userId);
        }
        for (UnionMobileTaskInfo mobileTaskInfo : unionMobileTaskList) {
            taskIds.add(mobileTaskInfo.getTaskId());
        }
        for (UserMobileTaskInfo mobileTaskInfo : unionMobileTaskInfos) {
            taskIds.add(mobileTaskInfo.getTaskId());
        }
        return taskIds;
    }

    /**
     * 随机获取指定数量的任务（支持过滤重复）
     *
     * @param num        需要获取的数量
     * @param excludeIds 需要排除的任务ID集合（可为null）
     * @return 随机且不重复的任务列表
     */
    public static List<Integer> randomTask(int num, Set<Integer> excludeIds) {
        // 1. 获取数据源
        ConcurrentHashMap<Integer, UnionactionMain> sourceMap = getUnionactionMainMap();
        if (sourceMap.isEmpty() || num <= 0) {
            return Collections.emptyList();
        }

        // 2. 构建候选列表（排除需过滤的ID）
        List<Integer> candidates = new ArrayList<>();
        for (UnionactionMain item : sourceMap.values()) {
            if (excludeIds == null || !excludeIds.contains(item.getId())) {
                candidates.add(item.getId());
            }
        }

        // 3. 数量不足时直接返回全部
        if (candidates.size() <= num) {
            return new ArrayList<>(candidates);
        }

        // 4. 随机选择（Fisher-Yates洗牌算法）
        List<Integer> result = new ArrayList<>(num);
        Random random = ThreadLocalRandom.current();

        // 复制候选列表避免修改原数据
        List<Integer> tempList = new ArrayList<>(candidates);

        for (int i = 0; i < num; i++) {
            // 随机交换元素到列表末尾
            int swapIndex = tempList.size() - 1 - i;
            int randomIndex = random.nextInt(tempList.size() - i);
            Collections.swap(tempList, randomIndex, swapIndex);

            // 取末尾元素加入结果
            result.add(tempList.get(swapIndex));
            if (excludeIds != null) {
                excludeIds.add(tempList.get(swapIndex));
            }
        }
        return result;
    }

    /**
     * 结算排行榜奖励
     *
     * @param act
     */
    public static void closeActUnionMobileRankReward(Act act) {
        // 发放单服排名奖励
        MainVerticle.logger.info("close actId start:" + act.getId());
        ConcurrentHashMap<Integer, ServerInfo> serverList = ServerManager.getServerList();
        int rankType = RankConstant.SERVER_RANK_MOBILE;
        long actId = act.getId();
        int groupId = Integer.parseInt(act.getParam());
        for (ServerInfo server : serverList.values()) {
            if (!server.isMerged() && act.isContainServer(server.getServerId())) {// 该服有开启联盟总动员
                int rankMaxNum = RankManager.getRankTypeMaxNum(rankType);
                JsonArray serverRankList = RankManager.getRankIdListByIndex(rankType, server.getServerId(), String.valueOf(act.getId()), 0, rankMaxNum - 1);
                MainVerticle.logger.info("## send  unionMobileRankReward reward actid = " + act.getId() + " rank size = " + serverRankList.size());
                for (int i = 0; i < serverRankList.size(); i++) {
                    int rank = i + 1;
                    long userId = Long.parseLong(serverRankList.getString(i));
                    RankReward rankReward = RankManager.getRankReward(rankType, rank, groupId);
                    if (rankReward != null) {
                        MainVerticle.logger.info("## send  unionMobileRankReward reward rankType " + rankType + " actid = " + actId + " rank = " + rank + " userId = " + userId);
                        String rankStr = rank + "";
                        MailManager.sendSystemMailReplaceContent(userId, MailConstant.RANK_UNION_MOBILE_TITLE, MailConstant.RANK_UNION_MOBILE_CONTENT, CommonUtils.takeReawrdItemFromStr(rankReward.getReward()), LogType.UNION_MOBILE_RANK_REWARD, rankStr);
                    }
                }

                if (!serverRankList.isEmpty()) {
                    String rankKey = RankManager.getRankName(rankType, server.getServerId(), (int) act.getId());
                    RedisTools.expire(rankKey, 2 * TimeUtils.WEEK);
                }
            }
        }

        // 发放跨服排名奖励
        JsonArray serverGroupIdList = ServerManager.getWarZoneIdList();// 所有的战区分组
        int crossRankType = RankConstant.SERVER_UNION_RANK_MOBILE;
        for (int gs = 0; gs < serverGroupIdList.size(); gs++) {
            int serverGroupId = serverGroupIdList.getInteger(gs);
            int crossRankMaxNum = RankManager.getRankTypeMaxNum(rankType);
            JsonArray crossServerRankList = RankManager.getRankIdListByIndex(crossRankType, serverGroupId, String.valueOf(act.getId()), 0, crossRankMaxNum - 1);
            MainVerticle.logger.info("## send  unionMobileCrossRankReward reward actid = " + act.getId() + " rank size = " + crossServerRankList.size());
            for (int i = 0; i < crossServerRankList.size(); i++) {
                int crossRank = i + 1;
                long userId = Long.parseLong(crossServerRankList.getString(i));
                RankReward rankReward = RankManager.getRankReward(crossRankType, crossRank, groupId);
                if (rankReward != null) {
                    MainVerticle.logger.info("## send  unionMobileCrossRankReward reward rankType " + crossRankType + " actid = " + actId + " rank = " + crossRank + " userId = " + userId);
                    String crossRankStr = crossRank + "";
                    MailManager.sendSystemMailReplaceContent(userId, MailConstant.RANK_UNION_MOBILE_UNION_TITLE, MailConstant.RANK_UNION_MOBILE_UNION_CONTENT, CommonUtils.takeReawrdItemFromStr(rankReward.getReward()), LogType.RANK_ACT_CONVENTION_REWARD, crossRankStr);
                }
            }

            if (crossServerRankList.size() > 0) {
                String rankKey = RankManager.getRankName(crossRankType, serverGroupId, act.getId());
                RedisTools.expire(rankKey, 2 * TimeUtils.WEEK);
            }
        }
    }


    /******************** 任务模块 **********************/

    /**
     * 通用、主线任务更新
     *
     * @param pbUserData
     * @param userInfo
     * @param taskType
     * @param num
     * @param param
     * @param isAdd
     */
    public static void updateTask(Common.PBUserData.Builder pbUserData, UserInfo userInfo, int taskType, long num, int param, boolean isAdd) {
        if (num <= 0) {
            return;
        }
        long userId = userInfo.getId();
        Act act = ActManager.getActByType(ActConstant.ACT_TYPE_1002, userInfo.getServerId());
        if (act == null || !act.isCloseTime()) {
            return;
        }
        UserMobileInfo userMobileInfo = getUserMobileInfo(userId);
        if (userMobileInfo.getTaskId() == 0) {   // 当前没有接取任务
            return;
        }
        int taskId = userMobileInfo.getTaskId();
        UnionactionMain unionactionMain = getUnionactionMain(taskId);
        if (unionactionMain == null) {  // 这个任务配置没有找到
            return;
        }
        if (unionactionMain.getTaskType() != taskType) {  // 任务类型不一致
            return;
        }
        if (!checkTaskType(unionactionMain, taskType, param)) {  // 检验特殊任务类型需要参数校验
            return;
        }
        handleTaskProgress(act, userInfo, unionactionMain, userMobileInfo, taskId, isAdd, num, pbUserData);
    }

    public static boolean checkTaskType(UnionactionMain unionactionMain, int taskType, int param) {
        if (taskType == MainTaskConstant.TASK_TYPE_258) {  // 购买礼包
            if (param < Integer.parseInt(unionactionMain.getSup())) {
                return false;
            }
        } else if (taskType == MainTaskConstant.TASK_TYPE_253) {
            if (param != Integer.parseInt(unionactionMain.getSup())) {
                return false;
            }
        }
        return true;
    }

    // 加入联盟处理
    public static void joinUnion(UserInfo userInfo, long unionId) {
        Act act = ActManager.getActByType(ActConstant.ACT_TYPE_1002, userInfo.getServerId());
        if (act == null || !act.isCloseTime()) {
            return;
        }
        UserMobileInfo userMobileInfo = getUserMobileInfo(userInfo.getId());
        if (userMobileInfo.getScore() > 0) {
            updateUnionMobileUserRank(act, userInfo, unionId, userMobileInfo.getScore());
        }
    }

    // 退出联盟处理
    public static void quitUnion(UserInfo userInfo, long unionId) {
        Act act = ActManager.getActByType(ActConstant.ACT_TYPE_1002, userInfo.getServerId());
        if (act == null || !act.isCloseTime()) {
            return;
        }
        long userId = userInfo.getId();
        // 玩家退出联盟，积分将会有40%的衰减
        UserMobileInfo userMobileInfo = getUserMobileInfo(userId);
        long subScore = userMobileInfo.getScore() * AllParam.UNIONMOBILE_QUIT_SCORE_DECR / 100;
        userMobileInfo.addScore(-subScore);  // 当前积分  不用塞给客户端，因为对应界面打开会再次获取
        userMobileInfo.update();
        updateUnionMobileUserRank(act, userInfo, unionId, -subScore);  // 个人与联盟同时扣除对应分数
    }


    // 清除活动数据
    public static void clearActData(Act act) {
        EntityManager.delEntity(UnionMobileTaskInfo.class);
        EntityManager.delEntity(UnionMobileInfo.class);
        EntityManager.delEntity(UserMobileTaskInfo.class);
        EntityManager.delEntity(UserMobileInfo.class);
    }
}
